import re
import serial
import pynmea2
from pynmea2 import parse
from pyproj import Transformer, CRS
import time
import os
import matplotlib.pyplot as plt

# 定义串口参数
# ser1_params = {
#     'port': '/dev/ttyUSB1',  # 串口1的路径，Windows上可能是'COM3'等
#     'baudrate': 115200,
#     'timeout': 1
# }

ser2_params = {
    'port': '/dev/ttyUSB0',  # 串口2的路径
    'baudrate': 115200,
    'timeout': 1
}

# 打开串口
# ser1 = serial.Serial(**ser1_params)
ser2 = serial.Serial(**ser2_params)

# 输出文件路径
output_file_path1 = os.path.join(os.path.expanduser('~'), 'Desktop', 'usb0.txt')
output_file_path2 = os.path.join(os.path.expanduser('~'), 'Desktop', 'usb1.txt')
output_file_path3 = os.path.join(os.path.expanduser('~'), 'Desktop', 'WGS84-UTM.txt')
output_file_path4 = os.path.join(os.path.expanduser('~'), 'Desktop', 'Extracted.txt')

# 假设UTM数据在文件中以"UTM Coordinates: X=..., Y=..."的格式出现
UTM_PATTERN = re.compile(r'UTM Coordinates: X=(\d+\.\d+), Y=(\d+\.\d+)')

# 创建一个空列表来存储提取的UTM数据（这里我们存储为(X, Y)元组的列表）
utm_data = []

# 用于存储UTM坐标的列表
utm_xs, utm_ys = [], []

# 记录开始时间
start_time = time.time()

# 设置源（WGS84）和目标（UTM，广州位于UTM 50N）坐标系
wgs84 = CRS("EPSG:4326")  # WGS 84
utm_zone_49n = CRS("EPSG:32649")  # UTM zone 49N

# 创建一个坐标转换器
transformer = Transformer.from_crs(wgs84, utm_zone_49n)

# 打开文件用于写入
with open(output_file_path1, 'w') as f1, open(output_file_path2, 'w') as f2:
    try:
        while True:
            if time.time() - start_time >= 300:  # 检查是否已经超过五分钟
                break  # 退出循环
            # 读取串口1的数据
            if ser1.in_waiting > 0:
                data1 = ser1.readline().decode('utf-8').rstrip()
                f1.write(data1 + '\n')
                # print(f"Received from Serial 1: {data1}")

                # 读取串口2的数据
            if ser2.in_waiting > 0:
                data2 = ser2.readline().decode('utf-8').rstrip()
                f2.write(data2 + '\n')

    except KeyboardInterrupt:
        print("Program stopped by user")

    finally:
        # 关闭串口
        ser1.close()
        ser2.close()

with open(output_file_path2, 'r', encoding='utf-8') as infile, open(output_file_path3, 'w') as outfile:
    for line in infile:
        sentence = parse(line)
        if isinstance(sentence, pynmea2.RMC):
            try:
                lat = sentence.latitude
                lon = sentence.longitude
                # GPRMC句子包含时间戳
                timestamp = sentence.timestamp.strftime('%Y-%m-%d %H:%M:%S')

                    # 检查经纬度是否在有效范围内
                if not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
                    continue

                    # 转换为UTM坐标
                utm_x, utm_y = transformer.transform(lat, lon)

                # 写入文件
                outfile.write(f"NMEA Time: {timestamp}\n")
                # outfile.write(f"Original Latitude: {lat:.6f}, Original Longitude: {lon:.6f}\n")
                outfile.write(f"UTM Coordinates: X={utm_x:.6f}, Y={utm_y:.6f}\n\n")

            except pynmea2.nmea.ChecksumError:
                # 忽略ChecksumError异常
                pass
            except pynmea2.ParseError:
                # 忽略无法解析的句子
                pass
            except Exception as e:
                # 捕获并打印其他异常
                print(f"An error occurred: {e}")

        # 打开并读取特定文件
with open(output_file_path3, 'r', encoding='utf-8') as file:
    content = file.read()
    # 使用正则表达式查找UTM数据
    matches = UTM_PATTERN.findall(content)
    utm_data.extend(matches)  # 将找到的UTM数据（作为元组）添加到列表中

# 将提取的UTM数据（X, Y坐标）写入新的文本文件，格式为"X, Y"
with open(output_file_path4, 'w', encoding='utf-8') as output_file:
    for utm in utm_data:
        output_file.write(f"{utm[0]}, {utm[1]}\n")  # 每个UTM数据占一行，格式为"X, Y"

print("UTM数据已提取并保存到文件'extracted_move.txt'中。")

# 读取文件并解析UTM数据
with open(output_file_path4, 'r', encoding='utf-8') as file:
    for line in file:
        # 假设每行包含一个UTM坐标对，格式为"X, Y"
        utm_data = line.strip().split(',')
        if len(utm_data) == 2:
            utm_x, utm_y = float(utm_data[0]), float(utm_data[1])
            utm_xs.append(utm_x)
            utm_ys.append(utm_y)

        # 绘制轨迹图
# plt.figure(figsize=(10, 6))  # 设置图形大小
# plt.plot(utm_xs, utm_ys, marker='o')  # 绘制轨迹线，并在每个点上添加标记
# plt.title('UTM Trajectory')  # 设置图形标题
# plt.xlabel('UTM X Coordinate')  # 设置X轴标签
# plt.ylabel('UTM Y Coordinate')  # 设置Y轴标签
# plt.grid(True)  # 显示网格线
# plt.show()  # 显示图形

# 绘制散点图
plt.scatter(utm_xs, utm_ys, label='UTM Data')
plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
plt.title('UTM Data Scatter Plot')
plt.legend()
plt.grid(True)
plt.show()